const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    orderId: null,
    orderInfo: {},
    paymentInfo: {},
    remainingTime: 0,
    countdownTimer: null
  },

  onLoad: function (options) {
    const orderId = options.orderId;
    this.setData({ orderId });
    console.log('🎯 支付页面加载，订单ID:', orderId);
    console.log('📋 页面参数:', options);

    this.loadOrderInfo();
  },

  onUnload: function () {
    // 清除倒计时
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
  },

  // 加载订单信息
  loadOrderInfo: function () {
    console.log('📦 开始加载订单信息');
    wx.request({
      url: buildUrl(`/api/orders/${this.data.orderId}`),
      method: 'GET',
      success: (res) => {
        console.log('📦 订单信息响应:', res.data);
        if (res.data.success) {
          this.setData({
            orderInfo: res.data.data
          });
          console.log('✅ 订单信息加载成功');
        } else {
          console.error('❌ 订单信息加载失败:', res.data.message);
          wx.showToast({
            title: '加载订单信息失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('💥 订单信息请求失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 处理支付：调用后端 /api/payments/create 创建微信支付订单，再使用 wx.requestPayment 拉起微信支付
  handlePayment: function () {
    const app = getApp ? getApp() : null;
    const userId = (app && app.globalData && app.globalData.userId) || wx.getStorageSync('userId');

    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    const amount = Number(this.data.orderInfo.final_fee || this.data.orderInfo.suggested_fee || this.data.orderInfo.amount || 0);

    if (!amount || amount <= 0) {
      wx.showToast({ title: '订单金额异常', icon: 'none' });
      return;
    }

    wx.showModal({
      title: '确认支付',
      content: `确认支付 ¥${amount.toFixed(2)} 吗？`,
      success: (res) => {
        if (!res.confirm) return;

        wx.showLoading({ title: '支付中...' });

        const openid = wx.getStorageSync('wechat_openid') || null;

        wx.request({
          url: buildUrl('/api/payments/create'),
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: {
            order_id: this.data.orderId,
            user_id: userId,
            amount: amount,
            payment_method: 'wechat',
            discount: 0,
            openid: openid
          },
          success: (res2) => {
            wx.hideLoading();
            const data = res2.data || {};
            if (data && data.success && data.data) {
              const payData = data.data;

              // 开发环境模拟支付：后端已直接标记订单完成
              if (payData.paymentType === 'mock' || !payData.paymentType) {
                wx.showToast({ title: '支付成功（测试环境）', icon: 'success' });
                setTimeout(() => {
                  wx.redirectTo({ url: `/pages/rating/rating?orderId=${this.data.orderId}` });
                }, 1000);
                return;
              }

              // 仅处理 JSAPI 小程序支付
              if (payData.paymentType === 'wechat_jsapi' && payData.params) {
                const p = payData.params;
                wx.requestPayment({
                  timeStamp: String(p.timeStamp || p.timestamp || ''),
                  nonceStr: p.nonceStr,
                  package: p.package,
                  signType: p.signType || 'MD5',
                  paySign: p.paySign,
                  success: () => {
                    wx.showToast({ title: '支付成功', icon: 'success' });
                    setTimeout(() => {
                      wx.redirectTo({ url: `/pages/rating/rating?orderId=${this.data.orderId}` });
                    }, 1000);
                  },
                  fail: (err) => {
                    console.error('微信支付失败:', err);
                    wx.showToast({ title: '支付已取消或失败', icon: 'none' });
                  }
                });
              } else {
                // 后端未返回 JSAPI 参数，暂不支持 H5/其他方式
                wx.showToast({ title: '暂不支持该支付方式', icon: 'none' });
              }
            } else {
              wx.showToast({ title: data.message || '支付失败', icon: 'none' });
            }
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('💥 支付请求失败:', err);
            wx.showToast({ title: '支付失败，请稍后重试', icon: 'none' });
          }
        });
      }
    });
  },

  // 格式化截止时间
  formatDeadline: function (deadlineString) {
    if (!deadlineString) return '';
    const date = new Date(deadlineString);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  },

  // 格式化倒计时
  formatCountdown: function (seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
});